package org.coc.iot.tag;

import lombok.extern.slf4j.Slf4j;
import org.coc.iot.constants.Constants;
import org.coc.iot.ehcache.CacheConfiguration;
import org.coc.iot.entity.SessionUser;
import org.coc.iot.entity.SysAction;
import org.coc.iot.entity.SysMenu;
import org.coc.iot.entity.SysUser;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Bean on 2017/5/19.
 */
@Slf4j
public class UserMenuTag {

    private static CacheConfiguration cacheConfiguration;

    public static void getInstance() {
        if(ObjectUtils.nullSafeEquals(cacheConfiguration, null)) {
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(attr.getRequest().getSession().getServletContext());
            cacheConfiguration = applicationContext.getBean(CacheConfiguration.class);
        }
    }

    /**
     * 用户菜单
     * @return
     */
    public static List<SysMenu> getMenuList() {
        getInstance();
        EhCacheCacheManager manager
                = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        SessionUser sessionUser = (SessionUser) attr.getRequest().getSession().getAttribute(Constants.SESSION_USER_KEY);
        Cache authorityCache = manager.getCache("authorityCache");
        String username = authorityCache.get(sessionUser.getToken(), String.class);
        Cache userMenuCache = manager.getCache("userMenuCache");
        List<SysMenu> menuList = userMenuCache.get(username, ArrayList.class);
        return menuList;
    }
}
